/*
 * Copyright [2013-2021], Alibaba Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.polardbx.gms.privilege.audit;

import com.alibaba.polardbx.gms.util.MetaDbUtil;
import com.google.common.base.Preconditions;
import com.alibaba.polardbx.common.audit.AuditAction;
import com.alibaba.polardbx.common.audit.AuditUtils;
import com.alibaba.polardbx.common.audit.ConnectionInfo;
import com.alibaba.polardbx.common.utils.logger.Logger;
import com.alibaba.polardbx.common.utils.logger.LoggerFactory;
import com.alibaba.polardbx.gms.metadb.audit.AuditLogAccessor;

import java.sql.Connection;
import java.sql.SQLException;

import static com.alibaba.polardbx.gms.privilege.PolarPrivUtil.POLAR_ROOT;

/**
 * @author hongxi.chx
 */
public class AuditPrivilege {
    private static final Logger LOG = LoggerFactory.getLogger(AuditPrivilege.class);

    private static boolean shouldLog(ConnectionInfo c) {
        Preconditions.checkNotNull(c, "Connection info can't be null!");
        return !POLAR_ROOT.equalsIgnoreCase(c.getUser());
    }

    public static void polarAudit(ConnectionInfo c, String auditInfo, AuditAction auditAction) {
        if (!shouldLog(c)) {
            return;
        }
        String log = String.format("%s,%s,%s,[%s]", c.getInstanceId(), c.getHost(), c.getUser(), auditInfo);
        AuditUtils.logAuditInfo(log, auditAction);
        polarAuditDb(c, auditInfo, auditAction);
    }

    public static void polarAuditDb(ConnectionInfo c, String auditInfo, AuditAction auditAction) {
        if (!shouldLog(c)) {
            return;
        }
        AuditLogAccessor auditLogAccessor = new AuditLogAccessor();
        try (Connection conn = MetaDbUtil.getConnection()) {
            auditLogAccessor.setConnection(conn);
            auditLogAccessor.addAuditLog(c.getUser(), c.getHost(), c.getPort(),
                c.getSchema(), auditInfo, auditAction, c.getTraceId());
        } catch (SQLException e) {
            LOG.error("Failed to persist audit info to db.", e);
        }
    }

    public static void audit(ConnectionInfo c, String auditInfo, AuditAction auditAction) {
        String log = String.format("%s,%s,%s,[%s]", c.getInstanceId(), c.getHost(), c.getUser(), auditInfo);
        AuditUtils.logAuditInfo(log, auditAction);
    }
}
